package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {

    @Autowired
    private ICategorySafeguardService categorySafeguardService;

    @Autowired
    private IPlanSafeguardService planSafeguardService;

//分页查询
    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //查询： list page count one
//        Page<Safeguard> page = this.lambdaQuery()
//                .eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()),Safeguard::getSafeguardKey,safeguardVO.getSafeguardKey())
//                .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()),Safeguard::getSafeguardKeyName,safeguardVO.getSafeguardKeyName())
//                .eq(StrUtil.isNotBlank(safeguardVO.getDataState()),Safeguard::getDataState,safeguardVO.getDataState())
//                .page(new Page<>(pageNum, pageSize));
        LambdaQueryWrapper<Safeguard> lqw = queryWrapper(safeguardVO);
        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), lqw);
        Page<SafeguardVO> voPage = BeanConv.toPage(page,SafeguardVO.class);
        return voPage;
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        //TODO
        return null;
    }

    //新增
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SafeguardVO save(SafeguardVO safeguardVO) {
        //新增接口，除了考虑新的数据，还要考虑是否合法
        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if (count>0){
            //说明key重复，不能新增
            log.error("新增保障项失败，因为key已经存在：{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        Safeguard bean = BeanConv.toBean(safeguardVO, Safeguard.class);
        this.save(bean);
        return BeanConv.toBean(bean,SafeguardVO.class);
    }

    //修改
    @Override
    @Transactional
    public Boolean update(SafeguardVO safeguardVO) {
        Safeguard bean = this.getById(safeguardVO.getId());
        if (bean == null){
            //没有数据
            log.error("数据不存在,{}",safeguardVO.getId());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //判断key不能重复
        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .ne(Safeguard::getId, safeguardVO.getId())
                .count();
        if (count>0){
            log.error("修改保障项失败，因为key已经存在：{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //判断冗余，查关系，只要有关系存在，就不让修改
        Integer count1 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if (count1>0 || count2>0){
            log.error("修改保障项失败，有关联关系：{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //代码走到这，检查全部通过，说明可以修改
        return updateById(BeanConv.toBean(safeguardVO,Safeguard.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(String[] checkedIds) {
        boolean result = false;
        //判断是否存在
        for (String id : checkedIds) {
            Safeguard bean = getById(id);
            if (bean==null){
                log.error("删除保障项失败,该数据不存在");
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
            //判断分类保障项和方案保障项是否存在关联项
            Integer count1 = categorySafeguardService.lambdaQuery()
                    .eq(CategorySafeguard::getSafeguardKey, bean.getSafeguardKey())
                    .count();
            Integer count2 = planSafeguardService.lambdaQuery()
                    .eq(PlanSafeguard::getSafeguardKey, bean.getSafeguardKey())
                    .count();
            if (count1>0 || count2>0){
                log.error("删除保障项失败，有关联关系");
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
             result = this.removeById(id);
        }
        return result;
    }

    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {

        LambdaQueryWrapper<Safeguard> lqw = queryWrapper(safeguardVO);
        List<Safeguard> list = this.list(lqw);
        return BeanConv.toBeanList(list,SafeguardVO.class);
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }

    private LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO){
        LambdaQueryWrapper<Safeguard> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()), Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()), Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                .eq(StrUtil.isNotBlank(safeguardVO.getDataState()), Safeguard::getDataState, safeguardVO.getDataState());
        return lqw;
}
